package org.willthink.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class DownloadView extends AbstractView {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		File file = (File) model.get("downloadFile");
		String realFileName = (String) model.get("realFileName");
		logger.debug("DownloadView file : {}", file);
		
		String userAgent = request.getHeader("User-Agent");
		    
		logger.debug("DownloadView getContentType() : {}", getContentType());
		
		response.setContentType("application/octet-stream");
		
		if (userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
			response.setHeader("Content-Disposition", "filename=\"" + 
					URLEncoder.encode(realFileName.trim(), "UTF-8") + ";"); // file.getName().trim()
		} else if (userAgent.indexOf("MSIE") > -1) { // MS IE (보통은 6.x 이상 가정)
			response.setHeader("Content-Disposition", "attachment; filename=\"" 
					+ java.net.URLEncoder.encode(realFileName.trim(), "UTF-8") + "\";");
		} else { // 모질라나 오페라
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ new String(realFileName.trim().getBytes("UTF-8"), "latin1") + "\";");
		}
		
		/*response.setHeader("Content-Disposition", "attachment;filename=\"" + 
				java.net.URLEncoder.encode(file.getName().trim(), "UTF-8")  + "\";");*/
		
		
		response.setHeader("Content-Transfer-Encoding", "binary"); 
		response.setContentLength((int) file.length());
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1;");
		
		OutputStream out = response.getOutputStream();

		FileInputStream fis = null;

		try {
			fis = new FileInputStream(file);
			/*
			byte[] imgBytes = new byte[fis.available()];
			fis.read(imgBytes);
			out.write(imgBytes, 0, imgBytes.length);
			out.flush();
			*/
			FileCopyUtils.copy(fis, out);
			out.flush();
			out.close();
		} catch (java.io.IOException ioe) {
			System.out.println("파일이 존재하지 않습니다.");
			ioe.printStackTrace();
		} finally {
			if (fis != null)
				fis.close();
			if (out != null)
				out.close();
		}
		
	}
	
}
